package ua.kharkiv.khpi.tarasenko.diploma.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileTransform {

    private File input;
    private File output;

    private static final String FILE_PARSE_PATTERN = "(\\d+)\\|(\\d+)\\|(\\d+)";

    public FileTransform(File input, File output) {
        if (input.exists()) {
            this.input = input;
            this.output = output;
        } else {
            System.err.println("File " + input + "doesn't exists!");
        }
    }

    public void transform() throws IOException {
        
        BufferedWriter writer = new BufferedWriter(new FileWriter(output));        
        
        BufferedReader reader = new BufferedReader(new FileReader(input));
        
        Pattern row = Pattern.compile(FILE_PARSE_PATTERN);
        String inputRow = "";
        Matcher m = null;
        String lastTransId = "";
        String currentTransId = "";
        //int numOfTrans = 120;
        while ((inputRow= reader.readLine())!=null) {
            m = row.matcher(inputRow);
            if (m.find()) {
                String transId = m.group(1);
                String itemId = m.group(2);
                String actionId = m.group(3);

                currentTransId = transId;
                if (currentTransId.equals(lastTransId)) {
                    writer.append(" " + itemId);
                } else {
//                    if (numOfTrans == 0) {
//                        break;
//                    }
                    
                    if (!lastTransId.equals("")) {
                    	writer.append(" " + "-2");                    	
                    	writer.newLine();
                    }
//                    numOfTrans--;
                    writer.append(itemId);      
                }
                
                lastTransId = currentTransId;
            }
        }
        writer.append(" " + "-2");                    	

        reader.close();
        writer.close();
    }
}
